package service;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import properties.MyAppConstantes;

import android.os.AsyncTask;
import beans.User;
import controller.MainActivity;

/**
 * @author ALENGUYE on recup infos user avc son id
 */
public class displayUserProfilAsyncTask extends AsyncTask<Object, Void, User> {
	private MainActivity Context = null;
	private String idUser;
	private String result;
	private String hash;
	private String timestamp;
	User user;

	public displayUserProfilAsyncTask(MainActivity context, String idUser) {
		super();
		Context = context;
		this.idUser = idUser;
	}

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected User doInBackground(Object... params) {

		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://" + MyAppConstantes.WsIpServer
				+ ":8080/ab_service_mgr/api/mobile/user/" + idUser);

		ResponseHandler<String> responseHandler = new BasicResponseHandler();

		httpPost.setHeader("content-type", "application/json");

		try {
			timestamp = System.currentTimeMillis() + "";
			hash = Sha1Utils.sha(MyAppConstantes.wsSecret + timestamp);

			JSONObject json = new JSONObject();
			json.put("timestamp", timestamp);
			json.put("hash", hash);
			json.put("wsCallerId", MyAppConstantes.wsCallerId);

			StringEntity entity = new StringEntity(json.toString());
			entity.setChunked(false);

			httpPost.setEntity(entity);
			httpPost.setHeader("Content-Type", "application/json");
			// entity.setContentEncoding("application/json");

			result = client.execute(httpPost, responseHandler);
			JSONObject jsonResp = new JSONObject(result);
			User user = new User(jsonResp.getString("identifiant"),
					jsonResp.getString("nom"), jsonResp.getString("prenom"),
					jsonResp.getString("dateNaissance"),
					jsonResp.getString("numeroRue"),
					jsonResp.getString("nomRue"), jsonResp.getString("tel"),
					jsonResp.getString("email"),
					jsonResp.getString("codePostal"),
					jsonResp.getString("ville"), jsonResp.getString("pays"),
					jsonResp.getString("latitude"),
					jsonResp.getString("longitude"),
					jsonResp.getString("photoURL"),
					jsonResp.getString("status"));
			 System.out.println("in doInBackground " + user.getPrenom() + " "
			 + user.getNom());
			 this.user = user;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.user;

	}

	protected void onPostExecute(User user) {
		 System.out.println("in onPostExecute" + user.getPrenom() + " "
		 + user.getNom());
		Context.setUser(user);
		Context.displayUserProfil(user);
	}
}
